const express = require('express')
const { renderToImage } = require('../controllers/imageController')
const { generateQRCode } = require('../utils')

module.exports = (server) => {
  const router = express.Router()

  router.get('/', async (req, res) => {
    // 生成二维码
    if (req.query.qr) {
      const qrOptions = { width: 86, margin: 0 }
      req.query.qr = await generateQRCode(req.query.qr, qrOptions)
    }

    // 从mysql中获取数据
    if (req.query.id && server.pool) {
      try {
        const sql = `SELECT * FROM yzm_article WHERE id = ${req.query.id} LIMIT 1`
        const data = await server.fetchData(sql)
        if (data.length) {
          req.query.data = data[0]
        }
      } catch (e) {
        // console.log("mysql error: ", e)
      }
    }

    res.render('index', req.query)
  })

  router.get(
    '/poster',
    (req, res, next) => {
      // 需要截图的页面RUL 宽度 高度 设备像素比
      req.poster = {
        page: '/',
        width: 600,
        height: 400,
        deviceScaleFactor: 2
      }

      req.poster.port = server.conf.serverPort
      next()
    },
    renderToImage
  )

  return router
}
